new Vue({
    el: '#permissions',
    data: function () {
        return {
            dialogVisible: false, //新建角色dialog
            addCharacterForm: true, //新建角色form
            addCharacterTree: true, //新建角色tree
            characterLists: [ //角色列表
                { 'id': 1, 'text': '管理员' },
                { 'id': 2, 'text': '超级管理员' },
                { 'id': 3, 'text': '访客' }
            ],
            characterCurrentIndex: 0, //角色列表currentLi
            nowEditCharacter: -1, //编辑角色名
            navListAuth: [], //权限管理数组
            defaultProps: { //tree设置
                children: 'children',
                label: 'text'
            },
            defaultExpandedKeys:[],//展开菜单的id
            defaultCheckedKeys:[],//当前角色对应勾选的菜单id
            ruleForm: { //form v-model
                name: ''
            },
            rules: { //from 验证
                name: [
                    { required: true, message:'请输入角色名称', trigger: 'blur'}
                ]
            },
            updateRoleObj:{},
            currentCheckRoleId:null,

            dialogIsShow:false,
            dialogMes:"",
            cancelShow:false
        };
    },
    created: function () {
        this.getAllResourceList();
        this.getAllRoleList();
    },
    methods: {
        /**
         * 获取资源列表
         */
        getAllResourceList:function () {
            var _this = this;
            $.ajax({
                url: '/findByParentResource',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    _this.navListAuth = res.data.rows
                    res.data.rows.forEach(function (obj) {
                        _this.defaultExpandedKeys.push(obj.id)
                    })
                },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                    errorMessage(_this.$message, '获取资源列表出错！')
                }
            })
        },
        /**
         * 获取角色列表
         */
        getAllRoleList:function () {
            var _this = this;
            $.ajax({
                url: '/findAllRole',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    _this.characterLists = res.data
                    console.info("角色列表：",_this.characterLists)
                    _this.currentCheckRoleId = _this.characterLists[0].id;
                    _this.getResourceByRoleId();
                },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                    errorMessage(_this.$message, '获取角色列表出错！')
                }
            })
        },
        /**
         * 新建角色下一步
         * @param formName
         */
        submitForm: function (formName) {
            var _this = this
            this.$refs[formName].validate(function (valid) {
                if (valid) {
                    _this.addCharacterForm = false
                    _this.addCharacterTree = true
                } else {
                    return false;
                }
            })
            console.log(formName+":"+_this.ruleForm)
        },
        /**
         * 保存新建角色
         */
        saveForm: function () {
            var _this = this
            console.info("点击了新建角色的保存按钮")


            var addCharacterTree = this.$refs.addCharacterTree.getCheckedKeys()
            console.log(addCharacterTree)

            if(addCharacterTree.length===0){
                warningMessage(_this.$message, '请选中至少一个权限！')
                return;
            }
            var resources = addCharacterTree.join(",");
            console.info("添加角色选中的权限菜单id："+resources);
            var roleName = this.ruleForm.name;
            console.info("添加的角色名称："+roleName)

            $.ajax({
                url: '/addRoleSource',
                type: 'post',
                data:{"resources":resources,"roleName":roleName},
                dataType: 'json',
                success: function (res) {
                    _this.dialogVisible = false
                    _this.getAllRoleList();
                    successMessage(_this.$message, '添加角色成功！')
                    // _this.showDialog(true,false,"！");
                },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                    errorMessage(_this.$message, '修改角色权限失败！')
                }
            })
        },
        /**
         * 新建角色
         */
        addCharacter: function () {
            this.dialogVisible = true
            this.addCharacterForm = true
            this.addCharacterTree = false
            this.ruleForm.name = ''
        },
        /**
         * 编辑角色权限
         * @param index
         */
        editPermissions: function (index,id) {
            console.info("点击了角色列表,角色id："+id);
            this.currentCheckRoleId=id;
            this.characterCurrentIndex = index;

            //根据角色id查询对应的权限
            this.getResourceByRoleId();
        },
        /**
         * 根据角色id查询对应的权限
         */
        getResourceByRoleId:function () {
            var _this = this;
            if(!_this.currentCheckRoleId){
                return;
            }
            $.ajax({
                url: '/getResourceByRoleId/'+_this.currentCheckRoleId,
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    _this.defaultCheckedKeys = res.data;
                    _this.$refs.navTree.setCheckedKeys(_this.defaultCheckedKeys)
                },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                    errorMessage(_this.$message, '查询对应的权限出错！')

                    // 提示：tipsMessage()
                    // 成功：successMessage()
                    // 警告：warningMessage()
                    // 错误：errorMessage()
                }
            })
        },
        /**
         * 修改角色名，把角色名变成可修改状态
         * @param id
         */
        changeCharacter: function (id) {
            this.nowEditCharacter = id
        },
        /**
         * 取消修改角色名
         */
        cancelEditCharacter: function () {
            this.nowEditCharacter = -1
        },
        /**
         *  取消修改角色权限
         */
        cancelUpdateRoleResource:function () {
            console.log("点击了取消修改权限")
            this.$refs.navTree.setCheckedKeys(this.defaultCheckedKeys)
        },
        /**
         *  显示弹窗提示信息
         *  dialogIsShow:是否显示弹窗
         *  cancelShow：是否显示弹窗中的取消按钮
         *  dialogMes：提示信息的内容
         */
        showDialog:function (dialogIsShow,cancelShow,dialogMes) {
            this.dialogIsShow=dialogIsShow;
            this.cancelShow=cancelShow;
            this.dialogMes=dialogMes;
        },
        /**
         *  确认修改角色权限
         */
        sureUpdateRoleResource:function () {
            var _this = this;
            var roleId = _this.characterLists[_this.characterCurrentIndex].id;
            //获取勾选的节点的id
            var checkedKeys = this.$refs.navTree.getCheckedKeys()
            if(checkedKeys.length===0){
                tipsMessage(_this.$message, '请选中至少一个权限！')
                return;
            }
            var resources = checkedKeys.join(",");

            $.ajax({
                url: '/updateRoleResourceByRoleId/'+roleId,
                type: 'post',
                data:{"resources":resources},
                dataType: 'json',
                success: function (res) {
                    // _this.showDialog(true,false,"");
                    successMessage(_this.$message, '权限修改成功！')
                },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                    errorMessage(_this.$message, '修改角色权限失败！')
                }
            })
        },
        /**
         * 确认修改角色名称
         * @param id
         */
        sureEditCharacter: function (id) {
            console.info("点击了确认修改角色名称");
            for (var i = 0; i < this.characterLists.length; i++) {
                if (id === this.characterLists[i]['id']){
                    this.characterLists.splice(i, 1, this.editCharacter)
                    this.updateRoleObj = this.editCharacter;
                    this.updateRoleNameById();
                    break
                }
            }
            this.nowEditCharacter = -1
        },
        /**
         * 根据id修改角色名称
         * @param id
         */
        updateRoleNameById:function () {
            var _this = this;
            if(this.updateRoleObj.id){
                console.log("修改后的角色id："+this.updateRoleObj.id+",修改后的角色名称:"+this.updateRoleObj.text);
                var roelId = this.updateRoleObj.id;
                var roleName = this.updateRoleObj.text;
                $.ajax({
                    url: '/updateRoleById/'+roelId,
                    data:{name:roleName},
                    type: 'post',
                    dataType: 'json',
                    success: function (res) {
                        // debugger
                        if(res.code!=0){
                            successMessage(_this.$message, '修改角色名成功！')
                            return;
                        }
                        successMessage(_this.$message, res.res)
                    },
                    error: function (err) {
                    	if(err.responseJSON.message=="session clean"){
                            errorMessage(_this.$message, '登陆已失效重新登陆!');
                            toLogin();
                            return;
                        }
                        // if(err.status==403){
                        //     // alert(err.responseJSON.message);
                        //     _this.showDialog(true,false,err.responseJSON.message);
                        //     return;
                        // }
                        // _this.showDialog(true,false,"修改角色名出错！");
                        errorMessage(_this.$message, '修改角色名出错！')


                    }
                })
            }
        }
        // handleClose:function(done) {
            // this.$confirm('确认关闭？')
            //     .then(function(){
            //         console.info("aaaaa")
            //         done();
            //
            //     }).catch(function(){
            //         console.info("1111111")
            // });
        // }
    },
    computed: {
        editCharacter: function () {
            var edit0 = {}
            for (var i = 0; i < this.characterLists.length; i++) {
                if (this.nowEditCharacter === this.characterLists[i]['id']) {
                    edit0 = this.characterLists[i]
                    break
                }
            }
            return {
                'id': edit0.id,
                'text': edit0.text
            }
        }
    }
})